import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import logging.handlers
from tornado.options import define, options
from config import LOGS_DIR, DEFAULT_SETTING_PATH
from blls.setting_blls.setting_bll import SettingBLL
from utils.db_util import CreateEngine

file_handler = logging.handlers.TimedRotatingFileHandler(LOGS_DIR,
                                                         when='midnight', backupCount=7, encoding='utf8')
console_handler = logging.StreamHandler()
# logging.disable(logging.DEBUG)
logging.getLogger().setLevel(logging.INFO)
logging.basicConfig(
    format="%(asctime)s %(levelname)s %(message)s",
    level=logging.INFO,
    datefmt="%Y-%m-%d %H:%M:%S",
    handlers=[file_handler, console_handler],
)


class Application(tornado.web.Application):
    def __init__(self):
        from handlers.urls import URLS
        handlers = URLS
        settings = dict()
        tornado.web.Application.__init__(self, handlers, **settings)
        self.db_session = self.get_sql_session("label")
        # self.get_init_site()
        logging.info("start")

    @staticmethod
    def get_sql_session(method="label"):
        engine = CreateEngine()
        return engine.get_engine(method)

    # @staticmethod
    # def get_init_site():
    #     init_site = SettingBLL().init_site_settings(DEFAULT_SETTING_PATH)
    #     return init_site

if __name__ == "__main__":
    define("port", default=8002, type=int)
    tornado.options.parse_command_line()
    app = Application()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()


